<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Amap;
use app\common\UsersService;
use app\model\Forum;
use app\model\ForumComment;
use app\model\ForumTags;
use app\model\UsersRelated;
use app\model\UsersShield;
use app\Request;
use think\db\Query;
use think\response\Json;

class ForumController extends BaseController
{
	
	
	protected array $middleware = ['Login' => [
		'except' => ['index', 'tag_index', 'read', 'comment_list'],
	]];
	
	/**
	 * 屏蔽
	 * @param Request $request
	 * @return void
	 */
	function shield(Request $request)
	{
		$id = $request->post('id/d');
		UsersShield::create([
			'users_id'=>$request->users_id,
			'pro_id'=>$id,
			'type'=>'forum'
		]);
		writeJson();
	}
	
	/**
	 * 论坛-列表
	 * @param int $type 1=新帖 2=热帖 3=话题
	 * @return Json
	 */
	public function index(Request $request, int $type, string $keyword): Json
	{
		if (in_array($type, [1, 2])) {
			
			$shield = UsersShield::where(['users_id'=>$request->users_id,'type'=>'forum'])->column('pro_id');
			$rows = Forum::with([
				'users',
				'users_follow' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id]);
				},
				'users_like' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id, 'type' => 'forum']);
				}])
				->when(!empty($type), function (Query $query) use ($type) {
					switch ($type) {
						case 1:
							$query->order('id', 'desc')->select();
							break;
						case 2:
							$query->order('browse', 'desc')->select();
							break;
					}
				})
				->whereNotIn('id',$shield)
				->when(!empty($keyword), function (Query $query) use ($keyword) {
					$query->whereLike('title|content', '%' . $keyword . '%');
				})
				->paginate()
				->items();
		} else {
			$rows = ForumTags::order('id', 'desc')
				->paginate()
				->items();
		}
		
		
		writeJson($rows);
	}
	
	/**
	 * 评论
	 * @param Request $request
	 * @return Json
	 */
	function comment(Request $request): Json
	{
		$params = $request->param();
		$ip = $request->ip();
		$params['ip'] = $ip;
		$ip = Amap::ip($ip);
		$ip = json_decode($ip);
		if ($ip->status == 1) {
			$params['city'] = $ip->province;
		} else {
			$params['city'] = '未知';
		}
		$res = ForumComment::create($params);
		foreach ($params['content'] as $v) {
			if ($v['type'] == 'at') {
				//@提醒  提醒接收人
				UsersRelated::create(['users_id' => $v['userId'], 'type' => 8, 'from_users_id' => $request->users_id, 'scene' => 'Forum', 'pro_id' => $res->id]);
			}
		}
		if (!empty($params['to_users_id'])) {
			//回复提醒  提醒接收人
			UsersRelated::create(['users_id' => $params['to_users_id'], 'type' => 1, 'from_users_id' => $request->users_id, 'scene' => 'Forum', 'pro_id' => $res->id]);
		} else {
			//评论提醒  提醒发布人
			$pro = Forum::find($params['forum_id']);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 2, 'from_users_id' => $request->users_id, 'scene' => 'Forum', 'pro_id' => $res->id]);
		}
		event('ForumIncComment', $params['forum_id']); //增加评论数量
		$row = ForumComment::with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
			$query->where(['users_id' => $request->users_id, 'type' => 'forum_comment']);
		}])->find($res->id);
		writeJson($row);
	}
	
	/**
	 * 评论列表
	 * @param int $forum_id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_list(int $forum_id, mixed $comment_id, Request $request)
	{
		$top_id = 0;
		if (!empty($comment_id)) {
			$row = ForumComment::find($comment_id);
			if ($row->pid == 0) {
				//顶级评论 放在第一条
				$top_id = $row->id;
			} else {
				//子评论 找出顶级评论
				$row = ForumComment::find($row->pid);
				$top_id = $row->id;
			}
		}
		$rows = ForumComment::where(['pid' => 0, 'forum_id' => $forum_id])
			->withCount('comment')
			->with([
				'users',
				'users_like' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id, 'type' => 'forum_comment']);
				},
				'comment' => function (Query $query) use ($request, $comment_id) {
					$query
						->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
							$query->where(['users_id' => $request->users_id, 'type' => 'forum_comment']);
						}])
						->when(!empty($comment_id), function (Query $query) use ($comment_id) {
							$query->field("*,IF(id = $comment_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
						}, function (Query $query) {
							$query->order(['id' => 'desc']);
						})
						->limit($this->comment_list_rows);
				}])
			->when(!empty($comment_id), function (Query $query) use ($top_id) {
				$query->field("IF(id = $top_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
			}, function (Query $query) {
				$query->order(['id' => 'desc']);
			})
			->paginate()
			->items();
		
		writeJson($rows);
	}
	
	/**
	 * 评论详情
	 * @param int $id
	 * @param Request $request
	 * @return Json
	 */
	function comment_detail(int $id, mixed $comment_id, Request $request)
	{
		$child = false;
		if (!empty($comment_id)) {
			$row = ForumComment::find($comment_id);
			if ($row->pid != 0) {
				//二级评论
				$child = true;
			}
		}
		$rows = ForumComment::where(['pid' => $id])
			->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'forum_comment']);
			}])
			->when($child, function (Query $query) use ($comment_id) {
				$query->where('id', '<>', $comment_id);
			})
			->order(['id' => 'desc'])
			->paginate($this->comment_detail_rows)
			->items();
		writeJson($rows);
	}
	
	/**
	 * 帖子详情
	 * @param Request $request
	 * @param int $id
	 * @return Json
	 */
	public function read(Request $request, int $id): Json
	{
		$row = Forum::with([
			'users',
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'forum']);
			},
			'users_collect' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'forum']);
			},
			'users_follow' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id]);
			}])->find($id);
		UsersService::footmark($id, $request->users_id, 'forum');
		event('ForumIncBrowse', $id); //增加浏览数量
		writeJson($row);
	}
	
	/**
	 * 论坛-发布
	 * @param Request $request
	 * @return Json
	 */
	public function save(Request $request)
	{
		$param = $request->param();
		Forum::create($param);
		writeJson();
	}
	
	
	/**
	 * 论坛-话题列表
	 * @return Json
	 */
	function tag_index()
	{
		$ForumTagsModel = new ForumTags();
		$rows = $ForumTagsModel->order('id', 'desc')->paginate()->items();
		writeJson($rows);
	}
	
	
	/**
	 * 话题详情
	 * @param string $city
	 * @param int $search
	 * @param int $id
	 * @return Json
	 */
	function topic(Request $request, string $city, int $search, int $id)
	{
		$tuijian = ForumTags::where(['is_good' => 1])->limit($this->page_rows)->order('id', 'desc')->select();
		$search = $search == 1 ? 'browse' : 'id';
		$rows = Forum::with([
			'users',
			'users_follow' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id]);
			},
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'forum']);
			},
		])
			->when(!empty($city), function (Query $query) use ($city) {
				$query->whereLike('address', '%' . $city . '%');
			})
			->whereFindInSet('tags_ids', $id)
			->order($search, 'desc')
			->paginate()
			->items();
		$res['tuijian'] = $tuijian;
		$res['detail'] = $rows;
		writeJson($res);
	}
	
	/**
	 * 评论点赞
	 * @param Request $request
	 * @return Json
	 */
	function comment_like(Request $request)
	{
		$id = $request->param('id');
		$res = UsersService::like($id, $request->users_id, 'forum_comment');
		$res ? event('ForumCommentIncLike', $id) : event('ForumCommentDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = ForumComment::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 4, 'from_users_id' => $request->users_id, 'scene' => 'Forum', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	/**
	 * 点赞
	 * @param Request $request
	 * @return Json
	 */
	function like(Request $request)
	{
		$id = $request->post('id');
		$res = UsersService::like($id, $request->users_id, 'forum');
		$res ? event('ForumIncLike', $id) : event('ForumDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = Forum::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 3, 'from_users_id' => $request->users_id, 'scene' => 'Forum', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	/**
	 * 收藏
	 * @param Request $request
	 * @return Json
	 */
	function collect(Request $request)
	{
		$id = $request->param('id');
		$res = UsersService::collect($id, $request->users_id, 'forum');
		$res ? event('ForumIncCollect', $id) : event('ForumDecCollect', $id); //增加/减少  收藏数量
		if ($res) {
			$pro = Forum::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'Forum', 'pro_id' => $id]);
		}
		writeJson($res);
	}
	
	/**
	 * 删除
	 * @param Request $request
	 * @return Json
	 */
	function delete(Request $request)
	{
		$id = $request->post('id/d');
		Forum::where(['users_id' => $request->users_id, 'id' => $id])->findOrFail()->delete();
		writeJson();
	}
}
